package com.wenx.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.TimeUnit;

/**
 * nio方式socketChnnelclient发送数据
 * Created by wenx on 2019-10-10 16:59
 */
public class SocketChannelClient {
    public static void main(String[] args) {
        client();
    }

    private static void client() {

        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        SocketChannel socketChannel = null;
        try {
            socketChannel = SocketChannel.open();
            //非阻塞方式
            socketChannel.configureBlocking(false);
            socketChannel.connect(new InetSocketAddress("localhost",8081));
            if(socketChannel.finishConnect()) {
                int i = 0;
                while (true) {
                    TimeUnit.SECONDS.sleep(1);
                    String msg = "I'm" + i++ +"-th msg from client";
                    byteBuffer.clear();
                    byteBuffer.put(msg.getBytes());
                    byteBuffer.flip();
                    while (byteBuffer.hasRemaining()) {
                        System.out.println(byteBuffer);
                        socketChannel.write(byteBuffer);
                    }
                }
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            if( socketChannel != null) {
                try {
                    socketChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}